/**
 * KAYO APPLIANCE CHAINS.
 * Copyright (c) 2016-2016 All Rights Reserved.
 */
package com.leku.mse.mq.listener.member;

import java.util.Set;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.leku.commons.datasource.DataSourceContextHolder;
import com.leku.commons.util.CollectionUtil;
import com.leku.commons.util.SenseWordUtil;
import com.leku.commons.util.StringUtil;
import com.leku.mse.constants.DataSourceConstant;
import com.leku.mse.dao.member.MemberDao;
import com.leku.mse.entity.MemberEntity;
import com.leku.mse.service.cache.MemberCache;
import com.leku.mse.service.cache.SenseWordCache;

/**
 * 功能描述: 会员数据同步监听
 *
 * @author suiying
 * @created 2017年6月5日
 * @version 1.0.0
 */
public class MemberSyncListener implements MessageListener {

    private static final Logger LOG = LoggerFactory.getLogger(MemberSyncListener.class);

    @Autowired
    private MemberDao memberManageDao;

    @Autowired
    private MemberCache memberCacheService;

    @Autowired
    private SenseWordCache senseWordCache;

    /*
     * (non-Javadoc)
     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
     */
    @Override
    public void onMessage(Message message) {
        MemberEntity member = null;
        String msg = null;
        try {
            TextMessage textMsg = (TextMessage) message;
            msg = textMsg.getText();
            LOG.info("会员基本消息:" + msg);
            member = JSON.parseObject(msg, MemberEntity.class);
        } catch (Exception e) {
            LOG.error("同步会员基本消息异常,消息为：" + msg, e);
        }

        if (member == null) {
            return;
        }

        if (StringUtil.isNotEmpty(member.getNick()) && wordFilter(member.getNick())) {
            member.setNick("**");
        }

        // 设置为会员中心数据库
        DataSourceContextHolder.setDataSourceType(DataSourceConstant.memDataSource());

        try {
            int updNum = memberManageDao.updateMemberBase(member);
            if (updNum == 0) {
                memberManageDao.insertMember(member);
            } else {
                // 更新缓存
                memberCacheService.resetMemberCache(member);
            }
        } catch (Exception e) {
            LOG.error("同步会员基本消息异常,消息为：" + msg, e);
        }
    }

    /**
     * 
     * 功能描述: 判断是否包含屏蔽字
     *
     * @param word
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean wordFilter(String word) {
        Set<String> words = senseWordCache.getMemSenseWord();

        boolean isSense = false;

        // 检查是否存在敏感词
        if (CollectionUtil.isNotEmpty(words)) {
            isSense = SenseWordUtil.isContaintSenseWord(word, SenseWordUtil.setSenseWordToMap(words));
        }

        return isSense;
    }
}
